package org.example.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.example.dao.BookingRecordDao;
import org.example.dao.InoculationRecordDao;
import org.example.dao.UserDao;
import org.example.domain.BookingRecord;
import org.example.domain.InoculationRecord;
import org.example.domain.User;
import org.example.service.InoculationRecordService;
import org.example.utils.ResponseUtil.ResponseResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.example.utils.ResponseUtil.StatusCode.DATA_NOT_EXIST;
import static org.example.utils.ResponseUtil.StatusCode.SERVICE_RUN_SUCCESS;

@Service
@Slf4j
public class InoculationRecordServiceImpl implements InoculationRecordService {

    @Resource
    private InoculationRecordDao inoculationRecordDao;

    @Resource
    private BookingRecordDao bookingRecordDao;

    @Resource
    private UserDao userDao;


    /**
     * 增加疫苗接种记录：通过预约记录的"确认接种"按钮。
     *
     * 点击预约记录表中，某行的 “接种完成”按钮后，
     * 获取当前行的用户user_uid 和预约时间booking_time，
     * 再根据系统的当前时间生成接种时间inoculate_time，根据当前用户的已经接种次数来确定当前的接种次数count，
     * 向数据库插入一条接种记录。
     *
     * 并根据当前行的预约记录的br_id，标记当前的预约记录为已经接种状态(inoculated=1),或将此预约记录进行物理删除。
     */
    @Override
    public ResponseResult insertInoculationByBooking(BookingRecord bookingRecord) {
        Integer bid = bookingRecord.getBr_id();//预约记录的id

        //检验预约记录的id,是否真实有效
        BookingRecord record = bookingRecordDao.selectBookingRecordById(bid);
        if (record == null){
            return new ResponseResult(DATA_NOT_EXIST, "疫苗预约记录的id无效，请检查！");
        }
        // 得到系统当前时间
        Date date = new Date();
        System.out.println("data = "+date.toString());
        //将时间格式化处理
        Timestamp timestamp = new  Timestamp(date.getTime());
        System.out.println("timestamp = "+timestamp.toString());
        //处理成数据库中，指定的字符串格式
        String time = timestamp.toString().substring(0,10)+" "+timestamp.toString().substring(11,19);
        System.out.println("time="+time);
        //向数据库中新增疫苗接种记录
        int count = inoculationRecordDao.countInoculationByUserId(bookingRecord.getUser_uid());//统计当前uid已经存在的接种记录
        InoculationRecord inoculationRecord = new InoculationRecord();
        inoculationRecord.setUser_uid(bookingRecord.getUser_uid());//用户id
        inoculationRecord.setCount(count+1);
        inoculationRecord.setBooking_time(bookingRecord.getBooking_time());
        inoculationRecord.setInoculate_time(time);
        int n = inoculationRecordDao.insertInoculationRecord(inoculationRecord);
        if (n>0){
            int i = bookingRecordDao.deleteBookingRecordById(bid);//删除预约记录
            return new ResponseResult(SERVICE_RUN_SUCCESS,inoculationRecord,
                    "id="+bookingRecord.getBr_id()+"的预约记录，已于"+time+"确认接种成功！");
        }
        else {
            return new ResponseResult(SERVICE_RUN_SUCCESS,inoculationRecord,
                    "id="+bookingRecord.getBr_id()+"的预约记录，确认接种失败！");
        }

    }



    /**
     * 增加 疫苗接种记录:
     * 不可缺少的数据是用户的User_uid。
     * 预约时间如果为空，为其赋默认值，
     * 接种时间如果为空，就为其赋系统的当前时间。
     * 接种次数会通过统计数据库中的已有接种次数获得。
     */
    @Override
    public ResponseResult insertInoculationRecord(InoculationRecord record) {
        Integer userId = record.getUser_uid();
        //首先去数据库查找，是否存在该账号id
        User u = userDao.selectUserById(userId);
        //如果不存在该账号
        if (u == null){
            return new ResponseResult(DATA_NOT_EXIST,
                    "系统中无 id="+userId+" 的账号！");
        }
        //如果用户id有效
        //处理预约时间
        if (record.getBooking_time()== null || "".equals(record.getBooking_time())){
            record.setBooking_time("无预约");
        }
        //处理接种时间
        if (record.getInoculate_time()== null || "".equals(record.getInoculate_time())){
            // 得到系统当前时间
            Date date = new Date();
            System.out.println("data = "+date.toString());
            //将时间格式化处理
            Timestamp timestamp = new  Timestamp(date.getTime());
            System.out.println("timestamp = "+timestamp.toString());
            //处理成数据库中，指定的字符串格式
            String time = timestamp.toString().substring(0,10)+" "+timestamp.toString().substring(11,19);
            System.out.println("time="+time);
            record.setInoculate_time(time);
        }
        //处理接种次数
        int count = inoculationRecordDao.countInoculationByUserId(userId);//统计当前uid已经存在的接种记录
        record.setCount(count+1);

        //执行插入操作
        int n =inoculationRecordDao.insertInoculationRecord(record);
        if (n>0){
            return new ResponseResult(SERVICE_RUN_SUCCESS,record,
                    userId+"号客户,新增疫苗接种记录成功！");
        }
        else {
            return new ResponseResult(DATA_NOT_EXIST,
                    userId+"号客户,新增疫苗接种记录失败！");

        }

    }


    /**
     * 修改 记录：根据接种记录的id
     */
    @Override
    public ResponseResult updateInoculationById(InoculationRecord record) {
        Integer id = record.getIr_id();
        if (id ==null || id == 0){
            return new ResponseResult(DATA_NOT_EXIST, "更新失败，疫苗接种记录的id值为空！");
        }
        //根据接种记录的id值，去数据库查找原来的数据
        InoculationRecord r = inoculationRecordDao.selectInoculationById(id);
        //如果前端传来对象的某个属性值为空，就把数据库中的原值存进去
        if (record.getUser_uid() == null || record.getUser_uid() == 0){
            record.setUser_uid(r.getUser_uid());
        }
        if (record.getCount() == null || record.getCount() == 0){
            record.setCount(r.getCount());
        }
        if (record.getBooking_time() == null || "".equals(record.getBooking_time() )){
            record.setBooking_time(r.getBooking_time());
        }
        if (record.getInoculate_time() == null || "".equals(record.getInoculate_time() )){
            record.setInoculate_time(r.getInoculate_time());
        }

        //执行真正的更新操作
        int n = inoculationRecordDao.updateInoculationById(record);
        if (n>0){
            return new ResponseResult(SERVICE_RUN_SUCCESS,record,
                    "id="+id+"的疫苗接种记录，更新成功！");
        }
        else {
            return new ResponseResult(DATA_NOT_EXIST,
                    "id="+id+"的疫苗接种记录，更新失败！");
        }
    }


    /**
     * 逻辑删除：根据接种记录表的ir_id
     */
    @Override
    public ResponseResult deleteInoculationById(Integer id) {
        int n = inoculationRecordDao.deleteInoculationById(id);
        if (n>0){
            return new ResponseResult(SERVICE_RUN_SUCCESS,n,
                    "id="+id+"的疫苗接种记录，删除成功！");
        }
        else {
            return new ResponseResult(DATA_NOT_EXIST,
                    "id="+id+"的疫苗接种记录，删除失败！");

        }
    }



    /**
     * 根据用户的账号，进行模糊查询
     */
    @Override
    public ResponseResult selectInoculationLikeUserAccount(String userAccount) {
        // 根据用户账号userAccount，模糊查询到多个user对象
        List<User> users = userDao.selectUserLikeAccount(userAccount);
        if (users == null || users.size() == 0){
            return new ResponseResult(DATA_NOT_EXIST,"无账号与'"+userAccount+"' 相关的疫苗接种记录！");
        }

        List<InoculationRecord> records = new ArrayList<>();
        int userId;
        //挨个遍历，获得user对象的userId，并根据userId获取到接种记录
        for (User user:users){
            userId = user.getUid();
            records.addAll(inoculationRecordDao.selectInoculationByUserId(userId));
        }
        if (records == null || records.size() == 0){
            return new ResponseResult(DATA_NOT_EXIST,"无账号与'"+userAccount+"' 相关的疫苗接种记录！");
        }
        else {
            return new ResponseResult(SERVICE_RUN_SUCCESS,records,"存在账号与'"+userAccount+"' 相关的疫苗接种记录！");
        }
    }


    /**
     * 根据用户的用户名username，进行模糊查询
     */
    @Override
    public ResponseResult selectInoculationLikeUsername(String username) {
        // 根据用户账号userAccount，模糊查询到多个user对象
        List<User> users = userDao.selectUserLikeUsername(username);
        if (users == null || users.size() == 0){
            return new ResponseResult(DATA_NOT_EXIST,"无用户名与'"+username+"' 相关的疫苗接种记录！");
        }

        List<InoculationRecord> records = new ArrayList<>();
        int userId;
        //挨个遍历，获得user对象的userId，并根据userId获取到接种记录
        for (User user:users){
            userId = user.getUid();
            records.addAll(inoculationRecordDao.selectInoculationByUserId(userId));
        }
        if (records == null || records.size() == 0){
            return new ResponseResult(DATA_NOT_EXIST,"无用户名与'"+username+"' 相关的疫苗接种记录！");
        }
        else {
            return new ResponseResult(SERVICE_RUN_SUCCESS,records,"存在用户名与'"+username+"' 相关的疫苗接种记录！");
        }
    }


    /**
     * 根据用户UserId查找多个接种记录
     */
    @Override
    public ResponseResult selectInoculationByUserId(Integer userId) {
        List<InoculationRecord> records = inoculationRecordDao.selectInoculationByUserId(userId);
        if (records == null || records.size() == 0){
            return new ResponseResult(DATA_NOT_EXIST,"无用户id="+userId+" 的疫苗接种记录");
        }
        else {
            return new ResponseResult(SERVICE_RUN_SUCCESS,records,"存在用户id="+userId+" 的疫苗接种记录");
        }
    }


    /**
     * 根据 接种日期inoculate_time，进行 模糊查询。
     * 模糊查询接种时间，只根据日期2022-01-15查，忽略后面的接种时间
     */
    @Override
    public ResponseResult selectInoculationLikeInoculate_time(String inoculateDate) {
        List<InoculationRecord> records = inoculationRecordDao.selectInoculationLikeInoculate_time(inoculateDate);
        if (records == null || records.size() == 0){
            return new ResponseResult(DATA_NOT_EXIST,inoculateDate+" 无接种记录");
        }
        else {
            return new ResponseResult(SERVICE_RUN_SUCCESS,records,inoculateDate+" 存在接种记录");
        }
    }


    /**
     * 根据接种次数count，查找多条接种记录
     */
    @Override
    public ResponseResult selectInoculationByCount(Integer count) {
        List<InoculationRecord> records = inoculationRecordDao.selectInoculationByCount(count);
        if (records == null || records.size() == 0){
            return new ResponseResult(DATA_NOT_EXIST,"无 第"+count+"次 接种的接种记录");
        }
        else {
            return new ResponseResult(SERVICE_RUN_SUCCESS,records,"存在 第"+count+"次 接种的接种记录");
        }
    }

    /**
     * 根据时间升序查询 所有疫苗接种记录
     */
    @Override
    public ResponseResult AscSelectAllByTime() {
        List records = inoculationRecordDao.AscSelectAllByTime();
        if (records == null || records.size() ==0 ){
            return new ResponseResult(DATA_NOT_EXIST,null,"疫苗接种列表为空！");
        }
        return new ResponseResult(SERVICE_RUN_SUCCESS, records,"疫苗接种列表升序查询成功");
    }


    /**
     * 根据时间降序查询 所有疫苗接种记录
     */
    @Override
    public ResponseResult DescSelectAllByTime() {
        List records = inoculationRecordDao.DescSelectAllByTime();
        if (records == null || records.size() ==0 ){
            return new ResponseResult(DATA_NOT_EXIST,null,"疫苗接种列表为空！");
        }
        return new ResponseResult(SERVICE_RUN_SUCCESS, records,"疫苗接种列表降序查询成功");
    }



    @Override
    public ResponseResult selectAllInoculation() {
        List records = inoculationRecordDao.selectAllInoculation();
        if (records == null || records.size() ==0 ){
            return new ResponseResult(DATA_NOT_EXIST,null,"疫苗接种列表为空！");
        }
        return new ResponseResult(SERVICE_RUN_SUCCESS, records,"疫苗接种列表查询成功");
    }


}
